//
//  OriginViewController.m
//  TourPlay
//
//  Created by dllo on 15/11/24.
//  Copyright © 2015年 王军岐. All rights reserved.
//

#import "OriginViewController.h"
#import "TodayHomeModel.h"
#import "TodayHomeCell.h"
#import "ActivitieDetailsViewController.h"

#define HEADIMAGEVIEW ((280 - 64) * AUTOSCREEN_HEIGHT)// 放大视图的高

@interface OriginViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *orgTableV;
@property (nonatomic, retain) UIView *viewHead;

@property (nonatomic, retain) UIImageView *imageViewHead;
@property (nonatomic, retain) UIVisualEffectView *blurView; //系统毛玻璃

@property (nonatomic, retain) UIView *NavigationView;

@property (nonatomic, retain) MBProgressHUD *hub;

@property (nonatomic, retain) NSMutableArray *orgArray;
@property (nonatomic, assign) NSInteger pIndex; // 上拉加载标记

@property (nonatomic, retain) UIButton *btnIng; // 进行中按钮
@property (nonatomic, retain) UIButton *btnEd; // 已结束按钮

@property (nonatomic, assign) NSInteger timeIndex; // 时间标签, 用于请求数据
@property (nonatomic, assign) BOOL mySelected; // 记录button状态

@property (nonatomic, retain) UIView *userHeadViewBack;

@property (nonatomic, retain) NSMutableArray *upArray; // 是否已经上拉加载完了

@property (nonatomic, assign) BOOL isUp;
@property (nonatomic, assign) BOOL isUpLoading; // 是否上拉加载

@property (nonatomic, retain) UIImageView *headImageV; // 用户头像
@property (nonatomic, retain) UILabel *userName; // 用户名

@end

@implementation OriginViewController
- (void)dealloc
{
    [_orgTableV release];
    [_viewHead release];
    [_imageViewHead release];
    [_NavigationView release];
    [_hub release];
    [_orgArray release];
    [_btnIng release];
    [_btnEd release];
    [_userHeadViewBack release];
    [_upArray release];
    [_activityMod release];
    
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 初始化一些参数
    self.isUp = YES;
    self.isUpLoading = NO;
    self.mySelected = YES;
    self.pIndex = 0;
    self.orgArray = [NSMutableArray array];
    self.upArray = [NSMutableArray array];
    

    
    UIView *viewBack = [[UIView alloc] initWithFrame:CGRectMake(17 * AUTOSCREEN_HEIGHT, 0, 1, self.view.frame.size.height)];
//    viewBack.backgroundColor = [UIColor colorWithRed:0.88 green:0.87 blue:0.88 alpha:1];
    [self.view addSubview:viewBack];
    [viewBack release];
    
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 64)];
    titleL.text = @"主办";
    titleL.backgroundColor = [UIColor clearColor];
    titleL.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleL;
    [titleL release];
    
    
    [self addColorChangedBlock:^{
        
        viewBack.normalBackgroundColor = [UIColor colorWithRed:0.88 green:0.87 blue:0.88 alpha:1];
        viewBack.nightBackgroundColor = [ColorSingleton shareSingleton].cellColor;
        
        titleL.nightTextColor = [ColorSingleton shareSingleton].navigationBarTextColor;
        titleL.normalTextColor = [ColorSingleton shareSingleton].navigationBarTextColor;
    }];
    
    
    NSLog(@"%ld",self.activityMod.orgid);
    
//    self.navigationController.automaticallyAdjustsScrollViewInsets = YES;

    
    self.automaticallyAdjustsScrollViewInsets = NO;
    NSLog(@"%d", self.automaticallyAdjustsScrollViewInsets);
    [self.navigationController.navigationBar  addSubview:self.NavigationView];
    [self.navigationController.navigationBar sendSubviewToBack:self.NavigationView];
    
    
    self.orgTableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    self.orgTableV.delegate = self;
    self.orgTableV.dataSource = self;
    [self.orgTableV registerClass:[TodayHomeCell class] forCellReuseIdentifier:@"cell"];
    self.orgTableV.backgroundColor = [UIColor clearColor];
    self.orgTableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.orgTableV];
    [_orgTableV release];

    
    self.viewHead = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEADIMAGEVIEW)];
    
    self.imageViewHead = [[UIImageView alloc] initWithFrame:self.viewHead.frame];
//    self.imageViewHead.image = [UIImage imageNamed:@"wode_morenbg@2x.jpg"];
    [self.viewHead addSubview:self.imageViewHead];
    
    self.orgTableV.tableHeaderView = self.viewHead;
    
    [_imageViewHead release];
    [_viewHead release];
    
    // 毛玻璃效果
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    self.blurView = [[UIVisualEffectView alloc] initWithEffect:effect];
    self.blurView.frame = self.imageViewHead.bounds;
    [self.viewHead addSubview:self.blurView];
    [_blurView release];
    

    
    
    self.timeIndex = 0;
    [self getUpdateWithTime:self.timeIndex];
    
    

    self.userHeadViewBack = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEADIMAGEVIEW)];
    self.userHeadViewBack.backgroundColor = [UIColor clearColor];
    [self.viewHead addSubview:self.userHeadViewBack];
    [_userHeadViewBack release];
    
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2.f - 1, (self.userHeadViewBack.frame.size.height - 80) / 2.f, 2, 80)];
    lineView.alpha = 0.5f;
    lineView.backgroundColor = [ColorSingleton shareSingleton].cellLineColor;
    [self.userHeadViewBack addSubview:lineView];
    [lineView release];

    
    self.headImageV = [[UIImageView alloc] initWithFrame:CGRectMake(lineView.frame.origin.x - lineView.frame.size.height - 20 - 30, lineView.frame.origin.y - 10, lineView.frame.size.height + 20, lineView.frame.size.height + 20)];
    self.headImageV.backgroundColor = [UIColor clearColor];
    // 裁掉边框
    self.headImageV.layer.masksToBounds = YES;
    self.headImageV.contentMode = UIViewContentModeScaleAspectFill;
    self.headImageV.layer.cornerRadius = self.headImageV.frame.size.height / 2.f;
    self.headImageV.layer.borderWidth = 5.0f;
    self.headImageV.layer.borderColor = [UIColor colorWithRed:0.75 green:0.64 blue:0.62 alpha:1].CGColor;
    self.headImageV.alpha = 1.0;
    [self.userHeadViewBack addSubview:self.headImageV];
    [_headImageV release];
    
    
    NSURL *url = [NSURL URLWithString:self.activityMod.orgavatar];
    [self.headImageV sd_setImageWithURL:url placeholderImage:PICHOLDEER];
    
    [self.imageViewHead sd_setImageWithURL:url placeholderImage:PICHOLDEER];
    
    

    
    self.userName = [[UILabel alloc] initWithFrame:CGRectMake(lineView.frame.origin.x + lineView.frame.size.width + 30, lineView.frame.origin.y + (lineView.frame.size.height - 40) / 2.f, SCREEN_WIDTH - lineView.frame.origin.x - 30 - 30, 40)];
//    self.userName.backgroundColor = [UIColor orangeColor];
    self.userName.font = [UIFont fontWithName:@"FZLTZCHJW--GB1-0" size:18.f];
    self.userName.textColor = [UIColor whiteColor];
    self.userName.text = self.activityMod.orgname;
    [self.userHeadViewBack addSubview:self.userName];
    [_userName release];
    
    
    [self addFooterRefresh];

}
#pragma mark - 上拉加载

-(void)addFooterRefresh
{   // 当上拉时候触发该方法
    self.orgTableV.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.pIndex++;
        self.isUp = YES;
        self.isUpLoading = YES;
        [self getUpdateWithTime:self.timeIndex];
    }];
}

- (void)leftAction
{
    [self.navigationController popViewControllerAnimated:YES];
    [self.NavigationView removeFromSuperview];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGFloat yOffset = self.orgTableV.contentOffset.y;
    //向上偏移量变正  向下偏移量变负
    if (yOffset < 0) {
        
        CGFloat factor = ABS(yOffset) + HEADIMAGEVIEW;
        CGRect f = CGRectMake(-([[UIScreen mainScreen] bounds].size.width * factor / HEADIMAGEVIEW - [[UIScreen mainScreen] bounds].size.width) / 2, -ABS(yOffset), [[UIScreen mainScreen] bounds].size.width * factor / HEADIMAGEVIEW, factor);
        
        self.imageViewHead.frame = f;
        self.blurView.frame = f;
    }
    

}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 65 * AUTOSCREEN_HEIGHT)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView *headBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, view.frame.size.height - 10  * AUTOSCREEN_HEIGHT)];
    headBackView.alpha = 0.95f;
    [view addSubview:headBackView];
    [headBackView release];
    
    [self addColorChangedBlock:^{
        
        headBackView.nightBackgroundColor = [ColorSingleton shareSingleton].cellColor;
        headBackView.normalBackgroundColor = [UIColor whiteColor];
    }];
    
    UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(10 * AUTOSCREEN_WIDTH, 0, SCREEN_WIDTH - 20 * AUTOSCREEN_WIDTH, 50 * AUTOSCREEN_HEIGHT)];
//    buttonView.backgroundColor = [UIColor orangeColor];
    [headBackView addSubview:buttonView];
    [buttonView release];
    
    self.btnIng = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnIng.frame = CGRectMake(50 * AUTOSCREEN_WIDTH, 10 * AUTOSCREEN_HEIGHT, buttonView.frame.size.width / 2.f - 75 * AUTOSCREEN_WIDTH, 35 * AUTOSCREEN_HEIGHT);
    
    if (self.mySelected) {
       self.btnIng.backgroundColor = [UIColor colorWithRed:0.42 green:0.33 blue:0.49 alpha:1];
    } else {
        self.btnIng.backgroundColor = [UIColor clearColor];
    }
    
    [self.btnIng setTitle:@"进行中" forState:UIControlStateNormal];
    [self.btnIng setTitleColor:[UIColor colorWithRed:0.45 green:0.42 blue:0.43 alpha:1] forState:UIControlStateNormal];
    [self.btnIng setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    self.btnIng.layer.cornerRadius = 18.f * AUTOSCREEN_HEIGHT;
    self.btnIng.titleLabel.font = [UIFont systemFontOfSize:16.f * AUTOSCREEN_HEIGHT];
    [self.btnIng addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.btnIng.tag = 1000;
    self.btnIng.selected = self.mySelected;
    [buttonView addSubview:self.btnIng];
    
    self.btnEd = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnEd.frame = CGRectMake(buttonView.frame.size.width - self.btnIng.frame.size.width - self.btnIng.frame.origin.x, self.btnIng.frame.origin.y, self.btnIng.frame.size.width, self.btnIng.frame.size.height);
    self.btnEd.layer.cornerRadius = self.btnIng.layer.cornerRadius;
    if (self.mySelected) {
         self.btnEd.backgroundColor = [UIColor clearColor];
    } else {
        self.btnEd.backgroundColor = [UIColor colorWithRed:0.42 green:0.33 blue:0.49 alpha:1];
    }
   
    [self.btnEd setTitle:@"已结束" forState:UIControlStateNormal];
    [self.btnEd setTitleColor:[UIColor colorWithRed:0.45 green:0.42 blue:0.43 alpha:1] forState:UIControlStateNormal];
    self.btnEd.titleLabel.font = self.btnIng.titleLabel.font;
    [self.btnEd setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.btnEd addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.btnEd.tag = 1001;
    self.btnEd.selected = !self.mySelected;
    [buttonView addSubview:self.btnEd];
    
    
    return view;
}
- (void)buttonAction:(UIButton *)sender
{
    if (!sender.selected) {
        
        self.btnEd.selected = !self.btnEd.selected;
        self.btnIng.selected = !self.btnIng.selected;
        
        self.mySelected = self.btnIng.selected; // 记录按钮状态
        
        NSLog(@"%d", self.mySelected);
        if (1000 ==  sender.tag) {
            self.btnEd.backgroundColor = [UIColor clearColor];
            self.pIndex = 0;
            self.timeIndex = 0;
            self.isUp = NO;
            [self getUpdateWithTime:self.timeIndex];
            
            
        } else {
            
            self.btnIng.backgroundColor = [UIColor clearColor];
            self.pIndex = 0;
            self.timeIndex = 3;
            self.isUp = NO;
            [self getUpdateWithTime:self.timeIndex];
        }
        
        sender.backgroundColor = [UIColor colorWithRed:0.42 green:0.33 blue:0.49 alpha:1];
        
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 65.f * AUTOSCREEN_HEIGHT;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (SCREEN_HEIGHT - 50 - 49 - 64) / 3.f;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.orgArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    TodayHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    
    cell.toDayMod = [self.orgArray objectAtIndex:indexPath.row];
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ActivitieDetailsViewController *activitieVC = [[ActivitieDetailsViewController alloc] init];
    // 隐藏
    activitieVC.hidesBottomBarWhenPushed = YES;
    activitieVC.activityId = [[self.orgArray objectAtIndex:indexPath.row] toDayId];
    activitieVC.activityTitle = [[self.orgArray objectAtIndex:indexPath.row] title];

    [self.navigationController pushViewController:activitieVC animated:YES];
    [activitieVC release];

}
#pragma mark - 获取数据
- (void)getUpdateWithTime:(NSInteger)time
{
    NSLog(@"time = %ld", time);
    NSString *url = [NSString stringWithFormat:@"http://wanapi.damai.cn/org/orglist.json?id=%ld&pindex=%ld&psize=20&source=%d&timestate=%ld&version=%d", self.activityMod.orgid, self.pIndex, URL_SOURCE, time, URL_VERSION];
    
    NSLog(@"%@", url);
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    // 让菊花旋转起来
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.hub show:YES];
    self.hub.labelText = @"努力加载中...";
    
    
    
    [AppTools getAFNet:url block:^(id result) {
        
        [self.upArray removeAllObjects];
        if (!self.isUp) {
            [self.orgArray removeAllObjects];
        }
        
        
        
        NSMutableDictionary *bigDic = result;
        

        
        for (NSMutableDictionary *dic in [bigDic objectForKey:@"data"]) {
            TodayHomeModel *orgMod = [TodayHomeModel modelWithDictionary:dic];
            [self.orgArray addObject:orgMod];
            [self.upArray addObject:orgMod];
        }
        
//        if (!self.isUpLoading) {
//
//            
//            TodayHomeModel *mod = [self.orgArray firstObject];
//            NSURL *url = [NSURL URLWithString:mod.orgavatar];
//            [self.headImageV sd_setImageWithURL:url placeholderImage:PICHOLDEER];
//            
//            [self.imageViewHead sd_setImageWithURL:url placeholderImage:PICHOLDEER];
//            
//            self.userName.text = mod.orgname;
//        }
        
        // 上拉加载, 是否加载完成判断, 注意执行顺序
        [self.orgTableV reloadData];
        
        // 停止上拉加载
        [self.orgTableV.footer endRefreshing];
        
        if (self.upArray.count < 20) {
            NSLog(@"隐藏");
            // 没有数据隐藏上拉
            self.orgTableV.footer.hidden = YES;
        }
        
        // 让菊花停止旋转
        [self.hub hide:YES];
    } errorBlock:^(NSError *error) {
        
        [self NetworkError:^{
            
            
        }];
        [self.hub hide:YES];
        // 停止下拉刷新
        [self.orgTableV.footer endRefreshing];
        NSLog(@"网络连接错误");
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
